package com.greenold.refunds.service.impl;

import java.util.List;

import com.greenold.common.core.domain.AjaxResult;
import com.greenold.common.utils.StringUtils;
import com.greenold.order.domain.Order;
import com.greenold.order.service.IOrderService;
import com.greenold.refunds.domain.RefundDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.greenold.refunds.mapper.RefundMapper;
import com.greenold.refunds.domain.Refund;
import com.greenold.refunds.service.IRefundService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 退款记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-14
 */
@Service
public class RefundServiceImpl implements IRefundService
{
    @Autowired
    private RefundMapper refundMapper;
    @Autowired
    private IOrderService orderService;


    /**
     * 查询退款记录
     *
     * @param id 退款记录主键
     * @return 退款记录
     */
    @Override
    public Refund selectRefundById(String id)
    {
        return refundMapper.selectRefundById(id);
    }

    /**
     * 查询退款记录列表
     *
     * @param refund 退款记录
     * @return 退款记录
     */
    @Override
    public List<Refund> selectRefundList(Refund refund)
    {

        return refundMapper.selectRefundList(refund);
    }

    /**
     * 新增退款记录
     *
     * @param refund 退款记录
     * @return 结果
     */
    @Override
    public int insertRefund(Refund refund)
    {
        return refundMapper.insertRefund(refund);
    }

    /**
     * 修改退款记录
     *
     * @param refund 退款记录
     * @return 结果
     */
    @Override
    public int updateRefund(Refund refund)
    {
        return refundMapper.updateRefund(refund);
    }

    /**
     * 批量删除退款记录
     *
     * @param ids 需要删除的退款记录主键
     * @return 结果
     */
    @Override
    public int deleteRefundByIds(String[] ids)
    {
        return refundMapper.deleteRefundByIds(ids);
    }

    /**
     * 删除退款记录信息
     *
     * @param id 退款记录主键
     * @return 结果
     */
    @Override
    public int deleteRefundById(String id)
    {
        return refundMapper.deleteRefundById(id);
    }

    @Override
    @Transactional // 事务：确保退款记录创建和订单状态更新原子性
    public AjaxResult applyRefund(Refund refund) {
        // 1. 修复：通过 orderId 查询订单（而非 refund.getId()）
        Order order = orderService.selectOrderById(refund.getOrderId());
        if (order == null) {
            return AjaxResult.error("关联订单不存在");
        }
        // 2. 生成18位退款码（调用订单服务的生成方法）
        String refundCode = orderService.generateSimpleRefundCode();
        refund.setRefundOrderNo(refundCode); // 将退款码设置到“本次退款订单号”字段

        // 2. 修复：已执行订单（orderStatus=2）必须填写退款原因（校验 refund.extend2，而非 order.extend2）
        if ("2".equals(order.getOrderStatus()) && StringUtils.isBlank(refund.getExtend2())) {

            return AjaxResult.error("已执行订单必须填写退款原因");
        }

        if("2".equals(order.getOrderStatus())){
            // 3. 修复：设置退款初始状态为“退款中”（对应前端状态映射：0=处理中）
            refund.setRefundStatus("0");
            refund.setExtend1("1"); // 关键：把订单状态同步到退款表
        }
        if("1".equals(order.getOrderStatus())){
            refund.setRefundStatus("1");
            refund.setExtend1("2"); // 关键：把订单状态同步到退款表
        }else{
            refund.setRefundStatus("2");
        }

        // 补充：关联订单的业务号（方便后续查询）
        refund.setBizOrderNo(order.getBizOrderNo());
        // 补充：设置申请人（从当前登录用户获取，若有）
        refund.setCreatedBy(order.getCustomerId());



        // 4. 创建退款记录
        int rows = refundMapper.insertRefund(refund);
        if (rows <= 0) {
            return AjaxResult.error("退款记录创建失败");
        }
        // 7. 调用订单服务，更新订单为“退款中”状态
        orderService.updateOrderForRefund(refund.getOrderId());


        return AjaxResult.success("退款申请提交成功");
    }



//    //退款列表渲染
    @Override
    public RefundDto selectRefundBybizOrderNo(String bizOrderNo) {
        // 实现代码（根据之前补充）
        RefundDto refund= new RefundDto();
        refund.setBizOrderNo(bizOrderNo);
        List<RefundDto> refunds = refundMapper.selectRefundListAddCustomerName(refund);
        return refunds.isEmpty() ? null : refunds.get(0);
    }
 //列表全部
    @Override
    public List<RefundDto> selectRefundListAll(RefundDto refundDto)
    {
       return refundMapper.selectRefundListAddCustomerName(refundDto);
    }




}